/**
 * 
 */
package com.edoomath.mainapp.tencent.web.controller.auth.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.demo2do.core.utils.StringUtils;
import com.edoomath.mainapp.tencent.handle.WebAuthHandler;

/**
 * @author downpour
 */
@Controller
@RequestMapping("/wechat/web-auth")
public class WebAuthListener {
    
    private static final Logger logger = LoggerFactory.getLogger(WebAuthListener.class);
    
    @Autowired
    private WebAuthHandler webAuthHandler;
    
    /**
     * 
     * @param code
     * @param state
     * @return
     */
    @RequestMapping(value = "/callback", method = RequestMethod.GET)
    public ModelAndView onTencentCallback(@RequestParam(value = "code", required = false) String code,
                                          @RequestParam(value = "state", required = false) String state) {
        
        ModelAndView modelAndView = new ModelAndView();
        
        logger.info("#onTencentCallBack - Starting to process tencent request with code[{}] and state[{}]", code, state);
        
        boolean success = webAuthHandler.validate(state);
        
        if(success) {
            
            // process code and state
            String url = webAuthHandler.process(code, state);
            
            logger.info("#onTencentCallBack - get process return url[{}]", url);
            
            modelAndView.setViewName(StringUtils.connect("redirect:", url));
            
            return modelAndView;
        }
        modelAndView.setViewName("/web-auth/error");
        return modelAndView;
    }

}
